package com.jsmtr.rms.controller;

import java.io.PrintWriter;
import java.util.*;
import java.util.stream.Collectors;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonObjectFormatVisitor;
import com.jsmtr.rms.entity.*;
import com.jsmtr.rms.utils.*;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import com.jsmtr.rms.entity.vo.JobVoDepartment;
import com.jsmtr.rms.service.ISysAdminService;
import com.jsmtr.rms.service.IUtilService;


@Controller
@RequestMapping("/SysAdmin")
public class SysAdminController {

    @Resource
    private ISysAdminService sysAdminService;

    @Resource
    private IUtilService utilService;

    //[start] 组织架构管理

    @RequestMapping("/changepwd")
    public String ChangePwd() {
        return "/SysAdmin/changepwd";
    }

    @RequestMapping("/saveChangePwd")
    public void SaveChangePwd(HttpServletRequest request, HttpServletResponse response) {
        BaseUser usr = utilService.getSessionUser(request);
        String upwd = request.getParameter("upwd");
        String npwd = request.getParameter("nupwd");
        if (usr == null) {
            utilService.printJsonResult(false, "请先登录系统！", "/login", response);
        } else {
            String md5upwd = StringTools.GetMD5Code(upwd);
            if (md5upwd.equalsIgnoreCase(usr.getUpwd())) {

                try {
                    if (StringTools.notEmpty(npwd)) {
                        usr.setUpwd(StringTools.GetMD5Code(npwd));
                        utilService.editObject(usr);
                        request.getSession().removeAttribute(RightInterceptor.SEESION_MEMBER);
                        request.getSession().removeAttribute(RightInterceptor.SEESION_RIGHT);
                        utilService.printJsonResult(true, "密码修改成功，请重新登录！", "/login", response);
                    } else {
                        utilService.printJsonResult(false, "新密码不能为空！", "no", response);
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                    utilService.printJsonResult(false, "操作失败！", "no", response);
                }


            } else {
                utilService.printJsonResult(false, "原密码输入错误！", "no", response);
            }
            usr.getUpwd();
        }


    }

    /*组织架构管理*/
    @RequestMapping("/department")
    public String BaseDepartment() {
        return "/SysAdmin/department";
    }

    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/getDepts")
    public void getDepts(HttpServletRequest request, HttpServletResponse response) {
        try {
            int perpage = Integer.parseInt(request.getParameter("perpage"));
            int page = Integer.parseInt(request.getParameter("page"));
            String code = request.getParameter("code");
            String name = request.getParameter("name");
            String fullname = request.getParameter("fullname");

            Map<String, Object> map = sysAdminService.selectBaseDepartments(page, perpage, code, name, fullname);
            StringBuilder result = new StringBuilder();
            double pageCount = (Double) map.get("pageCount");
            double allcount = (Double) map.get("count");
            if (pageCount != 0) {
                Object object = map.get("list");
                int num = 1;
                for (BaseDepartment dept : (List<BaseDepartment>) object) {
                    result.append("<tr><td>" + (perpage * (page - 1) + num) + "</td>");
                    result.append("<td>" + dept.getCode() + "</td>");
                    result.append("<td>" + dept.getName() + "</td>");
                    result.append("<td>" + dept.getFullname() + "</td></tr>");
                    num++;
                }
            } else {
                result.append("<tr style='display:none'><td></td></tr>");
            }
            result.append("<input type='hidden' id='pageCount' value='" + pageCount + "' />");
            result.append("<input type='hidden' id='allCount' value='" + allcount + "' />");
            utilService.printTextResult(result.toString(), response);
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printTextResult("<tr><td colspan='4'>读取数据失败</td></tr><input type='hidden' id='pageCount' value='0' /><input type='hidden' id='allCount' value='0' />", response);
        }
    }


    @RequestMapping(value = "/deptAdd")
    public String deptAdd(HttpServletRequest request, BaseDepartment baseDepartment, Model model) {
        if (baseDepartment.getCode() != null &&
                !baseDepartment.getCode().isEmpty()) {
            model.addAttribute("baseDepartment", baseDepartment);
            model.addAttribute("url", "departmentEdit");
        } else {
            model.addAttribute("url", "departmentAdd");
        }
        return "/SysAdmin/deptAdd";
    }

    @ResponseBody
    @RequestMapping(value = "/departmentAdd")
    public LayuiDataTableResultBean departmentAdd(BaseDepartment baseDepartment) {
        LayuiDataTableResultBean resultBean = new LayuiDataTableResultBean();
        try {
            baseDepartment.setDtype("0");
            utilService.addObject(baseDepartment);
        } catch (Exception e) {
            e.printStackTrace();
            resultBean.setCode(1);
            resultBean.setMsg("添加失败");
            return resultBean;
        }
        resultBean.setCode(0);
        resultBean.setMsg("添加成功");
        return resultBean;
    }

    @ResponseBody
    @RequestMapping(value = "/departmentEdit")
    public LayuiDataTableResultBean departmentEdit(BaseDepartment baseDepartment) {
        LayuiDataTableResultBean resultBean = new LayuiDataTableResultBean();
        try {
            baseDepartment.setDtype("0");
            utilService.editObject(baseDepartment);
        } catch (Exception e) {
            e.printStackTrace();
            resultBean.setCode(1);
            resultBean.setMsg("编辑失败");
            return resultBean;
        }
        resultBean.setCode(0);
        resultBean.setMsg("编辑成功");
        return resultBean;
    }

    @ResponseBody
    @RequestMapping(value = "/deptDel")
    public LayuiDataTableResultBean deptDel(@RequestBody List<BaseDepartment> baseDepartmentList) {
        LayuiDataTableResultBean resultBean = new LayuiDataTableResultBean();
        try {
            utilService.delList(baseDepartmentList);
        } catch (Exception e) {
            e.printStackTrace();
            resultBean.setCode(1);
            resultBean.setMsg("删除失败");
            return resultBean;
        }
        resultBean.setCode(0);
        resultBean.setMsg("删除成功");
        return resultBean;
    }

    @SuppressWarnings("unchecked")
    @ResponseBody
    @RequestMapping(value = "/getDeptsLayuiJson")
    public LayuiDataTableResultBean getDeptsLayuiJson(HttpServletRequest request, HttpServletResponse response) {
        try {
            int page = Integer.parseInt(request.getParameter("page"));
            int limit = Integer.parseInt(request.getParameter("limit"));
            String code = request.getParameter("code");
            String name = request.getParameter("name");
            String fullname = request.getParameter("fullname");

            Map<String, Object> map = sysAdminService.selectBaseDepartments(page, limit, code, name, fullname);

            LayuiDataTableResultBean result = new LayuiDataTableResultBean();
            result.setCode(0);
            result.setMsg("success");
            result.setCount(((Double) map.get("count")).intValue());
            result.setData(map.get("list"));
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            LayuiDataTableResultBean result = new LayuiDataTableResultBean();
            result.setCount(-1);
            result.setMsg("err");
            return result;
        }
    }

    @ResponseBody
    @RequestMapping(value = "/getDeptsJson")
    public ResultBean getDeptsJson(HttpServletRequest request, HttpServletResponse response) {
        ResultBean resultBean = new ResultBean();
        try {
            //int perpage = Integer.parseInt(request.getParameter("perpage"));
            //int page = Integer.parseInt(request.getParameter("page"));
            String code = request.getParameter("code");
            String name = request.getParameter("name");
            String fullname = request.getParameter("fullname");

            Map<String, Object> map = sysAdminService.selectBaseDepartments(1, 100, code, name, fullname);
            if (map != null && map.size() > 0) {
                resultBean.setState(true);
                resultBean.setMessage("操作成功");
                resultBean.setDatas(map.get("list"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            resultBean.setState(false);
            resultBean.setMessage("操作失败");
        }
        return resultBean;
    }

    @SuppressWarnings("unchecked")
    @ResponseBody
    @RequestMapping(value = "/getDepartmentJson")
    public LayuiDataTableResultBean getDepartmentJson(HttpServletRequest request, HttpServletResponse response) {
        LayuiDataTableResultBean result = new LayuiDataTableResultBean();
        try {
            int page = Integer.parseInt(request.getParameter("page"));
            int limit = Integer.parseInt(request.getParameter("limit"));
            String code = request.getParameter("code");
            String name = request.getParameter("name");
            String fullname = request.getParameter("fullname");

            Map<String, Object> map = sysAdminService.selectBaseDepartments(page, limit, code, name, fullname);

            List<BaseDepartment> list = (List<BaseDepartment>) map.get("list");
            List<Object> data = new ArrayList<>();
            for (BaseDepartment bd :
                    list) {
                data.add(JSONObject.fromObject(bd));
            }

            result.setCode(0);
            result.setMsg("success");
            result.setCount(((Double) map.get("count")).intValue());
            result.setData(map.get("list"));
        } catch (Exception e) {
            e.printStackTrace();
            result.setCount(-1);
            result.setMsg("err");
        }
        return result;
    }

    /*选择部门*/
    @RequestMapping("/getdepts")
    public String getdepts() {
        return "/SysAdmin/getdepts";
    }

    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/getDeptLists")
    public void getDeptLists(HttpServletRequest request, HttpServletResponse response) {
        try {
            int perpage = Integer.parseInt(request.getParameter("perpage"));
            int page = Integer.parseInt(request.getParameter("page"));
            String code = request.getParameter("code");
            String name = request.getParameter("name");
            String fullname = request.getParameter("fullname");

            Map<String, Object> map = sysAdminService.selectBaseDepartments(page, perpage, code, name, fullname);
            StringBuilder result = new StringBuilder();
            double pageCount = (Double) map.get("pageCount");
            double allcount = (Double) map.get("count");
            if (pageCount != 0) {
                Object object = map.get("list");
                int num = 1;
                for (BaseDepartment dept : (List<BaseDepartment>) object) {
                    result.append("<tr><td>" + (perpage * (page - 1) + num) + "</td>");
                    result.append("<td>" + dept.getCode() + "</td>");
                    result.append("<td>" + dept.getName() + "</td>");
                    result.append("<td>" + dept.getFullname() + "</td>");
                    result.append("<td class='link'><a href='javascript:'>选择</a></td></tr>");
                    num++;
                }
            } else {
                result.append("<tr style='display:none'><td></td></tr>");
            }
            result.append("<input type='hidden' id='pageCount' value='" + pageCount + "' />");
            result.append("<input type='hidden' id='allCount' value='" + allcount + "' />");
            utilService.printTextResult(result.toString(), response);
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printTextResult("<tr><td colspan='5'>读取数据失败</td></tr><input type='hidden' id='pageCount' value='0' /><input type='hidden' id='allCount' value='0' />", response);
        }
    }

    //[end]

    //[start] 岗位管理

    /*岗位管理*/
    @RequestMapping("/job")
    public String BaseJob() {
        return "/SysAdmin/job";
    }

    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/getJobs")
    public void getJobs(HttpServletRequest request, HttpServletResponse response) {
        try {
            int perpage = Integer.parseInt(request.getParameter("perpage"));
            int page = Integer.parseInt(request.getParameter("page"));
            String code = request.getParameter("code");
            String name = request.getParameter("name");
            String deptcode = request.getParameter("deptcode");

            Map<String, Object> map = sysAdminService.selectBaseJobs(page, perpage, code, name, deptcode);
            StringBuilder result = new StringBuilder();
            double pageCount = (Double) map.get("pageCount");
            double allcount = (Double) map.get("count");
            if (pageCount != 0) {
                Object object = map.get("list");
                int num = 1;
                for (JobVoDepartment job : (List<JobVoDepartment>) object) {
                    result.append("<tr><td>" + (perpage * (page - 1) + num) + "</td>");
                    result.append("<td>" + job.getCode() + "</td>");
                    result.append("<td>" + job.getName() + "</td>");
                    result.append("<td>" + job.getDeptname() + "</td></tr>");
                    num++;
                }
            } else {
                result.append("<tr style='display:none'><td></td></tr>");
            }
            result.append("<input type='hidden' id='pageCount' value='" + pageCount + "' />");
            result.append("<input type='hidden' id='allCount' value='" + allcount + "' />");
            utilService.printTextResult(result.toString(), response);
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printTextResult("<tr><td colspan='4'>读取数据失败</td></tr><input type='hidden' id='pageCount' value='0' /><input type='hidden' id='allCount' value='0' />", response);
        }
    }

    @ResponseBody
    @RequestMapping(value = "/getJobsJson")
    public ResultBean getJobsJson(HttpServletRequest request, HttpServletResponse response) {
        ResultBean resultBean = new ResultBean();
        try {
            //int perpage = Integer.parseInt(request.getParameter("perpage"));
            //int page = Integer.parseInt(request.getParameter("page"));
            String code = request.getParameter("code");
            String name = request.getParameter("name");
            String deptcode = request.getParameter("deptcode");

            Map<String, Object> map = sysAdminService.getAllJobs(1, 100);
            if (map != null && map.size() > 0) {
                resultBean.setState(true);
                resultBean.setMessage("操作成功");
                resultBean.setDatas(map.get("list"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            resultBean.setState(false);
            resultBean.setMessage("操作失败");
        }
        return resultBean;
    }

    @ResponseBody
    @RequestMapping(value = "/getTypesJson")
    public ResultBean getTypesJson(HttpServletRequest request, HttpServletResponse response) {
        ResultBean resultBean = new ResultBean();
        try {
            String name = request.getParameter("jobnameSelect");

            BaseJob baseJob = sysAdminService.getjobByName(name);
            if (baseJob != null) {
                resultBean.setState(true);
                resultBean.setMessage("操作成功");
                resultBean.setDatas(baseJob);
            }
        } catch (Exception e) {
            e.printStackTrace();
            resultBean.setState(false);
            resultBean.setMessage("操作失败");
        }
        return resultBean;
    }



    @ResponseBody
    @RequestMapping(value = "/getPoliticals")
    public ResultBean getPoliticals(HttpServletRequest request, HttpServletResponse response) {
        ResultBean resultBean = new ResultBean();
        try {
            List<BaseData> baseDataList = sysAdminService.getPoliticals();
            if (baseDataList != null) {
                resultBean.setState(true);
                resultBean.setMessage("操作成功");
                resultBean.setDatas(baseDataList);
            }
        } catch (Exception e) {
            e.printStackTrace();
            resultBean.setState(false);
            resultBean.setMessage("操作失败");
        }
        return resultBean;
    }

    @ResponseBody
    @RequestMapping(value = "/getJobsLayuiJson")
    public LayuiDataTableResultBean getJobsLayuiJson(HttpServletRequest request, HttpServletResponse response) {
        LayuiDataTableResultBean result = new LayuiDataTableResultBean();
        try {
            int page = Integer.parseInt(request.getParameter("page"));
            int limit = Integer.parseInt(request.getParameter("limit"));

            String code = request.getParameter("code");
            String name = request.getParameter("name");
            String deptcode = request.getParameter("deptcode");

            Map<String, Object> map = sysAdminService.selectBaseJobs(page, limit, code, name, deptcode);

            result.setCode(0);
            result.setMsg("success");
            result.setCount(((Double) map.get("count")).intValue());
            result.setData(map.get("list"));
        } catch (Exception e) {
            e.printStackTrace();
            result.setCount(-1);
            result.setMsg("err");
        }
        return result;
    }

    /*选择岗位*/
    @RequestMapping("/getjobs")
    public String getjobs() {
        return "/SysAdmin/getjobs";
    }

    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/getJobLists")
    public void getJobLists(HttpServletRequest request, HttpServletResponse response) {
        try {
            int perpage = Integer.parseInt(request.getParameter("perpage"));
            int page = Integer.parseInt(request.getParameter("page"));
            String code = request.getParameter("code");
            String name = request.getParameter("name");
            String deptcode = request.getParameter("deptcode");

            Map<String, Object> map = sysAdminService.selectBaseJobs(page, perpage, code, name, deptcode);
            StringBuilder result = new StringBuilder();
            double pageCount = (Double) map.get("pageCount");
            double allcount = (Double) map.get("count");

            if (pageCount != 0) {
                Object object = map.get("list");
                int num = 1;
                for (JobVoDepartment job : (List<JobVoDepartment>) object) {
                    result.append("<tr><td>" + (perpage * (page - 1) + num) + "</td>");
                    result.append("<td>" + job.getCode() + "</td>");
                    result.append("<td>" + job.getName() + "</td>");
                    result.append("<td>" + job.getDeptname() + "</td>");
                    result.append("<td class='link'><a href='javascript:'>选择</a></td></tr>");
                    num++;
                }
            } else {
                result.append("<tr style='display:none'><td></td></tr>");
            }
            result.append("<input type='hidden' id='pageCount' value='" + pageCount + "' />");
            result.append("<input type='hidden' id='allCount' value='" + allcount + "' />");
            utilService.printTextResult(result.toString(), response);
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printTextResult("<tr><td colspan='5'>读取数据失败</td></tr><input type='hidden' id='pageCount' value='0' /><input type='hidden' id='allCount' value='0' />", response);
        }
    }

    @RequestMapping("/jobAdd")
    public String jobAdd(JobVoDepartment jvd, Model model) {
        if (jvd.getCode() != null &&
                !jvd.getCode().isEmpty()) {
            model.addAttribute("job", jvd);
            model.addAttribute("url", "jobEditUpdata");
        } else {
            model.addAttribute("url", "jobAddCreate");
        }
        return "SysAdmin/jobAdd";
    }

    @ResponseBody
    @RequestMapping("/jobAddCreate")
    public LayuiDataTableResultBean jobAddCreate(BaseJob job) {
        LayuiDataTableResultBean resultBean = new LayuiDataTableResultBean();
        try {
            job.setPcount(0);
            job.setRcount(0);
            job.setEditdate(new Date());
            job.setJobseries("0");
            job.setJobrank("0");
            job.setId(utilService.getJobMaxID() + 1);
            utilService.addObject(job);
            resultBean.setMsg("添加岗位成功");
            resultBean.setCode(0);
        } catch (Exception e) {
            e.printStackTrace();
            resultBean.setMsg("添加岗位失败");
            resultBean.setCode(1);
        }
        return resultBean;
    }

    @ResponseBody
    @RequestMapping("/jobEditUpdata")
    public LayuiDataTableResultBean jobEditUpdata(BaseJob job) {
        LayuiDataTableResultBean resultBean = new LayuiDataTableResultBean();
        try {
            BaseJob po = sysAdminService.getJobById(job.getId());
            po.setCode(job.getCode());
            po.setName(job.getName());
            po.setDeptcode(job.getDeptcode());
            po.setType(job.getType());
            utilService.editObject(po);
            resultBean.setMsg("编辑岗位成功");
            resultBean.setCode(0);
        } catch (Exception e) {
            e.printStackTrace();
            resultBean.setMsg("编辑岗位失败");
            resultBean.setCode(1);
        }
        return resultBean;
    }

    @ResponseBody
    @RequestMapping("/jobDel")
    public LayuiDataTableResultBean jobDel(@RequestBody List<BaseJob> jobs) {
        LayuiDataTableResultBean resultBean = new LayuiDataTableResultBean();
        try {
            List<BaseJob> poList = new ArrayList<>();
            for (BaseJob job :
                    jobs) {
                poList.add(sysAdminService.getJobById(job.getId()));
            }
            utilService.delList(poList);
            resultBean.setCode(1);
            resultBean.setMsg("删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            resultBean.setCode(-1);
            resultBean.setMsg("删除失败");
        }
        return resultBean;
    }

    //[end]

    //[start] 用户管理

    //[start] 用户列表
    @RequestMapping("/users")
    public String Users() {
        return "/SysAdmin/users";
    }

    @SuppressWarnings("unchecked")
    @RequestMapping("/getusers")
    public void getUsers(HttpServletRequest request, HttpServletResponse response) {
        try {
            int perpage = Integer.parseInt(request.getParameter("perpage"));
            int page = Integer.parseInt(request.getParameter("page"));
            String code = request.getParameter("code");
            String name = request.getParameter("name");
            String deptcode = request.getParameter("deptcode");

            Map<String, Object> map = sysAdminService.selectBaseUsers(page, perpage, code, name, deptcode);
            StringBuilder result = new StringBuilder();
            double pageCount = (Double) map.get("pageCount");
            double allcount = (Double) map.get("count");
            if (pageCount != 0) {
                Object object = map.get("list");
                int num = 1;
                for (BaseUser usr : (List<BaseUser>) object) {
                    result.append("<tr><td><input type=\"checkbox\" id=\"cb_" + usr.getId() + "\" /></td>");
                    result.append("<td>" + (perpage * (page - 1) + num) + "</td>");
                    result.append("<td>" + usr.getUcode() + "</td>");
                    result.append("<td>" + usr.getUname() + "</td>");
                    result.append("<td>" + usr.getUtel() + "</td>");
                    result.append("<td>" + usr.getUdeptname() + "</td><td>");

                    List<String> roles = sysAdminService.getBaseUserRole(usr.getId());
                    for (String role : roles) {
                        result.append(role + " ");
                    }

                    result.append("</td><td>" + DateTools.toShortStr(usr.getAddtime()) + "</td>");
                    if (usr.getUstate() == 0) {
                        result.append("<td class='false'>");
                    } else {
                        result.append("<td class='true'>");
                    }
                    result.append("<span>" + EnumTools.State.values()[usr.getUstate()] + "</span></td></tr>");
                    num++;
                }
            } else {
                result.append("<tr style='display:none'><td></td></tr>");
            }
            result.append("<input type='hidden' id='pageCount' value='" + pageCount + "' />");
            result.append("<input type='hidden' id='allCount' value='" + allcount + "' />");
            utilService.printTextResult(result.toString(), response);
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printTextResult("<tr><td colspan='8'>读取数据失败</td></tr><input type='hidden' id='pageCount' value='0' /><input type='hidden' id='allCount' value='0' />", response);
        }
    }

    @SuppressWarnings("unchecked")
    @ResponseBody
    @RequestMapping(value = "/getusersLayuiJson")
    public LayuiDataTableResultBean getusersLayuiJson(HttpServletRequest request, HttpServletResponse response) {
        try {
            int page = Integer.parseInt(request.getParameter("page"));
            int limit = Integer.parseInt(request.getParameter("limit"));
            String code = request.getParameter("code");
            String name = request.getParameter("name");
            String deptcode = request.getParameter("deptcode");

            Map<String, Object> map = sysAdminService.selectBaseUsers(page, limit, code, name, deptcode);

            LayuiDataTableResultBean result = new LayuiDataTableResultBean();
            JSONArray data = new JSONArray();
            List<BaseUser> list = (List<BaseUser>) map.get("list");

            for (BaseUser user :
                    list) {
                JSONObject item = JSONObject.fromObject(user);
                List<String> roles = sysAdminService.getBaseUserRole(user.getId());
                StringBuilder rolesBuilder = new StringBuilder(16);
                for (String st :
                        roles) {
                    rolesBuilder.append(st);
                    rolesBuilder.append(" ");
                }
                item.put("userole", rolesBuilder.toString());
                item.put("stateS", EnumTools.State.values()[user.getUstate()]);
                item.put("datetime", DateTools.toShortStr(user.getAddtime()));
                data.add(item);
            }

            result.setCode(0);
            result.setMsg("success");
            result.setCount(((Double) map.get("count")).intValue());
            result.setData(data);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            LayuiDataTableResultBean result = new LayuiDataTableResultBean();
            result.setCount(-1);
            result.setMsg("err");
            return result;
        }
    }

    //[end]

    //[start] 添加用户
    @RequestMapping("/useradd")
    public String UserAdd(Model model) {
        try {
            List<BaseRole> roles = sysAdminService.getRoles();
            model.addAttribute("roles", roles);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "/SysAdmin/useradd";
    }

    @SuppressWarnings({"rawtypes", "unchecked"})
    @RequestMapping(value = "/AddUser", method = RequestMethod.POST)
    public void AddUser(HttpServletRequest request, HttpServletResponse response) {
        try {
            String ucode = request.getParameter("ucode").trim();
            if (sysAdminService.getUser(ucode) == null) {
                List addList = new ArrayList();

                BaseUser usr = utilService.getSessionUser(request);
                String id = UUID.randomUUID().toString();
                BaseUser baseUser = new BaseUser();
                Date tDate = new Date();
                baseUser.setId(id);
                baseUser.setUcode(ucode);
                baseUser.setUname(request.getParameter("uname").trim());
                baseUser.setUtel(request.getParameter("utel").trim());
                baseUser.setUdept(request.getParameter("deptcode").trim());
                baseUser.setUdeptname(request.getParameter("deptname").trim());
                baseUser.setUpwd(StringTools.GetMD5Code(request.getParameter("upwd").trim()));
                baseUser.setAddtime(tDate);
                baseUser.setAdduid(usr.getId());
                baseUser.setAdduname(usr.getUname());
                baseUser.setEdittime(tDate);
                baseUser.setEdituid(usr.getId());
                baseUser.setEdituname(usr.getUname());
                baseUser.setUstate(EnumTools.State.启用.ordinal());

                addList.add(baseUser);

                String[] rids = request.getParameterValues("rid");
                for (String rid : rids) {
                    BaseUserRole urole = new BaseUserRole();
                    urole.setId(UUID.randomUUID().toString());
                    urole.setRoleid(rid);
                    urole.setUserid(id);
                    addList.add(urole);
                }

                utilService.addList(addList);
                utilService.printJsonResult(true, "操作成功", "no", response);
            } else {
                utilService.printJsonResult(false, "操作失败，员工号重复！", "no", response);
            }
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printJsonResult(false, "操作失败", "no", response);
        }
    }

    //[end]

    //[start] 修改用户
    @RequestMapping("/useredit")
    public String UserEdit(HttpServletRequest request, Model model) {
        try {
            String id = request.getParameter("id").trim();
            model.addAttribute("user", sysAdminService.getUserById(id));
            model.addAttribute("roles", sysAdminService.getRoles());

            StringBuilder str = new StringBuilder();
            List<BaseUserRole> uRoles = sysAdminService.getBaseUserRoles(id);
            for (BaseUserRole uRole : uRoles) {
                str.append("<input type='hidden' value='" + uRole.getRoleid() + "'/>");
            }
            model.addAttribute("uroles", str);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "/SysAdmin/useredit";
    }

    @SuppressWarnings({"rawtypes", "unchecked"})
    @RequestMapping(value = "/EditUser", method = RequestMethod.POST)
    public void EditUser(HttpServletRequest request, HttpServletResponse response) {
        try {
            String id = request.getParameter("id").trim();
            Date tDate = new Date();
            BaseUser usr = utilService.getSessionUser(request);
            BaseUser user = sysAdminService.getUserById(id);

            user.setUtel(request.getParameter("utel").trim());
            user.setUdept(request.getParameter("deptcode").trim());
            user.setUdeptname(request.getParameter("deptname").trim());
            user.setEdittime(tDate);
            user.setEdituid(usr.getId());
            user.setEdituname(usr.getUname());

            List addList = new ArrayList();
            String[] rids = request.getParameterValues("rid");
            for (String rid : rids) {
                BaseUserRole urole = new BaseUserRole();
                urole.setId(UUID.randomUUID().toString());
                urole.setRoleid(rid);
                urole.setUserid(id);
                addList.add(urole);
            }

            utilService.editList(user, sysAdminService.getBaseUserRoles(id), addList);
            utilService.printJsonResult(true, "操作成功", "no", response);
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printJsonResult(false, "操作失败", "no", response);
        }
    }
    //[end]

    //[start] 启用/禁用用户

    @RequestMapping(value = "/EnableUser", method = RequestMethod.POST)
    public void EnableUser(HttpServletRequest request, HttpServletResponse response) {
        try {
            String[] ids = request.getParameterValues("id");
            if (ids != null) {
                List<BaseUser> users = sysAdminService.getUsers(ids);
                for (BaseUser user : users) {
                    if (user.getUstate() == EnumTools.State.启用.ordinal()) {
                        user.setUstate(EnumTools.State.禁用.ordinal());
                    } else {
                        user.setUstate(EnumTools.State.启用.ordinal());
                    }
                }
                utilService.editList(users);
                utilService.printJsonResult(true, "操作成功", "no", response);
            } else {
                utilService.printJsonResult(false, "请选择用户信息", "no", response);
            }
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printJsonResult(false, "操作失败", "no", response);
        }
    }

    //[end]

    //[start] 重置密码

    @RequestMapping(value = "/ResetPwd", method = RequestMethod.POST)
    public void ResetPwd(HttpServletRequest request, HttpServletResponse response) {
        try {
            String[] ids = request.getParameterValues("id");
            if (ids != null) {
                List<BaseUser> users = sysAdminService.getUsers(ids);
                String pwd = StringTools.GetMD5Code("111111");
                for (BaseUser user : users) {
                    user.setUpwd(pwd);
                }
                utilService.editList(users);
                utilService.printJsonResult(true, "操作成功", "no", response);
            } else {
                utilService.printJsonResult(false, "请选择用户信息", "no", response);
            }
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printJsonResult(false, "操作失败", "no", response);
        }
    }

    //[end]

    //[end]

    //[start] 角色管理

    //[start] 角色信息列表

    /*角色管理*/
    @RequestMapping("/roles")
    public String Roles() {
        return "/SysAdmin/roles";
    }

    @SuppressWarnings("unchecked")
    @RequestMapping("/getroles")
    public void getRoles(HttpServletRequest request, HttpServletResponse response) {
        try {
            int perpage = Integer.parseInt(request.getParameter("perpage"));
            int page = Integer.parseInt(request.getParameter("page"));
            String rname = request.getParameter("rname");

            Map<String, Object> map = sysAdminService.selectBaseRoles(page, perpage, rname);
            StringBuilder result = new StringBuilder();
            double pageCount = (Double) map.get("pageCount");
            double allcount = (Double) map.get("count");
            if (pageCount != 0) {
                Object object = map.get("list");
                int num = 1;
                for (BaseRole role : (List<BaseRole>) object) {
                    result.append("<tr><td><input type=\"checkbox\" id=\"cb_" + role.getId() + "\" /></td>");
                    result.append("<td>" + (perpage * (page - 1) + num) + "</td>");
                    result.append("<td>" + role.getRname() + "</td>");
                    result.append("<td>" + EnumTools.Rtype.values()[role.getRtype()] + "</td>");
                    result.append("<td>" + role.getRemark() + "</td></tr>");
                    num++;
                }
            } else {
                result.append("<tr style='display:none'><td></td></tr>");
            }
            result.append("<input type='hidden' id='pageCount' value='" + pageCount + "' />");
            result.append("<input type='hidden' id='allCount' value='" + allcount + "' />");
            utilService.printTextResult(result.toString(), response);
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printTextResult("<tr><td colspan='5'>读取数据失败</td></tr><input type='hidden' id='pageCount' value='0' /><input type='hidden' id='allCount' value='0' />", response);
        }
    }

    @SuppressWarnings("unchecked")
    @ResponseBody
    @RequestMapping(value = "/getRolesLayuiJson")
    public LayuiDataTableResultBean getRolesLayuiJson(HttpServletRequest request, HttpServletResponse response) {
        try {
            int page = Integer.parseInt(request.getParameter("page"));
            int limit = Integer.parseInt(request.getParameter("limit"));
            String rname = request.getParameter("rname");

            Map<String, Object> map = sysAdminService.selectBaseRoles(page, limit, rname);
            List<BaseRole> list = (List<BaseRole>) map.get("list");
            JSONArray jsonArray = new JSONArray();

            for (BaseRole role :
                    list) {
                JSONObject item = JSONObject.fromObject(role);
                item.replace("rtype", EnumTools.Rtype.values()[role.getRtype()]);
                jsonArray.add(item);
            }
            LayuiDataTableResultBean result = new LayuiDataTableResultBean();
            result.setCode(0);
            result.setMsg("success");
            result.setCount(((Double) map.get("count")).intValue());
            result.setData(jsonArray);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            LayuiDataTableResultBean result = new LayuiDataTableResultBean();
            result.setCount(-1);
            result.setMsg("err");
            return result;
        }
    }

    //[end]

    //[start] 添加角色

    /*添加角色*/
    @RequestMapping("/roleadd")
    public String AddRole() {
        return "/SysAdmin/roleadd";
    }

    @RequestMapping("/AddRoleAction")
    public void AddRoleAction(HttpServletRequest request, HttpServletResponse response) {
        try {
            String id = UUID.randomUUID().toString();
            String rname = request.getParameter("rname").trim();
            String remark = request.getParameter("remark").trim();

            BaseRole baseRole = new BaseRole();
            baseRole.setId(id);
            baseRole.setRname(rname);
            baseRole.setRemark(remark);
            baseRole.setRtype(EnumTools.Rtype.用户角色.ordinal());

            utilService.addObject(baseRole);

            utilService.printJsonResult(true, "操作成功", "no", response);
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printJsonResult(false, "操作失败", "no", response);
        }
    }

    //[end]

    //[start] 修改角色

    @RequestMapping("/roleedit")
    public String EditRole(HttpServletRequest request, Model model) {
        try {
            String id = request.getParameter("id").trim();
            BaseRole role = sysAdminService.getRole(id);
            model.addAttribute("role", role);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "/SysAdmin/roleedit";
    }

    @RequestMapping("/EditRoleAction")
    public void EditRoleAction(HttpServletRequest request, HttpServletResponse response) {
        try {
            String id = request.getParameter("id").trim();
            BaseRole role = sysAdminService.getRole(id);
            if (role.getRtype() == EnumTools.Rtype.用户角色.ordinal()) {
                role.setRname(request.getParameter("rname").trim());
                role.setRemark(request.getParameter("remark").trim());

                utilService.editObject(role);
                utilService.printJsonResult(true, "操作成功", "no", response);
            } else {
                utilService.printJsonResult(false, "系统角色不能修改", "no", response);
            }
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printJsonResult(false, "操作失败", "no", response);
        }
    }

    //[end]

    //[start] 删除角色

    @SuppressWarnings({"rawtypes", "unchecked"})
    @RequestMapping("/DelRoleAction")
    public void DelRoleAction(HttpServletRequest request, HttpServletResponse response) {
        try {
            List delList = new ArrayList();
            String[] ids = request.getParameterValues("id");
            if (ids != null) {
                List<BaseRole> roles = sysAdminService.getRoles(ids);
                for (BaseRole role : roles) {
                    if (role.getRtype() == EnumTools.Rtype.用户角色.ordinal()) {
                        delList.add(role);
                        delList.addAll(sysAdminService.getBaseRoleModulars(role.getId()));
                        delList.addAll(sysAdminService.getUserRoles(role.getId()));
                    }
                }

                utilService.delList(delList);
                utilService.printJsonResult(true, "操作成功", "no", response);
            } else {
                utilService.printJsonResult(false, "请选择需要执行此操作的信息", "no", response);
            }
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printJsonResult(false, "操作失败", "no", response);
        }
    }

    //[end]

    //[start] 角色权限分配

    @RequestMapping("/roleright")
    public String roleright(HttpServletRequest request, Model model) {
        try {
            String rid = request.getParameter("id").trim();
            model.addAttribute("role", sysAdminService.getRole(rid));
            StringBuilder str = new StringBuilder();
            List<BaseModular> modulars = sysAdminService.getBaseModulars(0);
            int i = 0;
            for (BaseModular modular : modulars) {
                str.append("<tr style='background:#F3F3F3;'><td><div class='radio1'><span rel='pub_" + i + "'>" + modular.getMname() + "<input type='checkbox' name='mid' value='" + modular.getId() + "'/></span></div></td></tr>");
                List<BaseModular> _modulars = sysAdminService.getBaseModulars(modular.getId());
                if (_modulars.size() > 0) {
                    str.append("<tr style='background:#FFF;'><td><div class='radio1' style='padding-left:20px;'>");
                    for (BaseModular _modular : _modulars) {
                        str.append("<span rel='sub_" + i + "'>" + _modular.getMname() + "<input type='checkbox' name='mid' value='" + _modular.getId() + "'/></span>");
                    }
                    str.append("</div></td></tr>");
                }
                i++;
            }
            model.addAttribute("result", str);

            List<BaseRoleModular> mlist = sysAdminService.getBaseRoleModulars(rid);
            StringBuilder mids = new StringBuilder();
            for (BaseRoleModular modular : mlist) {
                mids.append("<input type='hidden' value='" + modular.getMid() + "' />");
            }
            model.addAttribute("mids", mids);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return "/SysAdmin/roleright";
    }

    @RequestMapping(value = "/RoleRightAction", method = RequestMethod.POST)
    public void RoleRightAction(HttpServletRequest request, HttpServletResponse response) {
        try {
            String id = request.getParameter("id").trim();
            BaseRole role = sysAdminService.getRole(id);
            if (role.getRtype() == EnumTools.Rtype.系统角色.ordinal()) {
                utilService.printJsonResult(false, "系统角色权限不能修改！", "no", response);
            } else {
                String[] mids = request.getParameterValues("mid");
                if (mids != null) {
                    List<BaseRoleModular> addList = new ArrayList<BaseRoleModular>();
                    for (String mid : mids) {
                        BaseRoleModular rmodular = new BaseRoleModular();
                        rmodular.setId(UUID.randomUUID().toString());
                        rmodular.setMid(Integer.parseInt(mid));
                        rmodular.setRid(id);
                        addList.add(rmodular);
                    }
                    List<BaseRoleModular> rmodulars = sysAdminService.getBaseRoleModulars(id);
                    utilService.addList(rmodulars, addList);
                    utilService.printJsonResult(true, "权限分配成功！", "no", response);
                } else {
                    utilService.printJsonResult(false, "请选择权限！", "no", response);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printJsonResult(false, "权限分配失败！", "no", response);
        }
    }

    //[end]

    //[end]

    @RequestMapping(value = "/jump2oa", method = RequestMethod.POST)
    public void jump2oa(HttpServletRequest request, HttpServletResponse response) {
        try {
            BaseUser currentUser = utilService.getSessionUser(request);
            PrintWriter writer = response.getWriter();
            String code = DESUtil.encrypt(currentUser.getUcode());
            writer.write("http://113.204.103.171:8384/seeyon/ssoIndex.jsp?code=" + code);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
